// ignore_for_file: use_build_context_synchronously, prefer_typing_uninitialized_variables

import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:wallpaper_app/api/update.dart';

class UpdateApk {
  String updateUrl = 'https://gitee.com/zsnoin-can/desktop_exe';
  var loadingBot;

  Future updateApk(BuildContext context, {bool displayTips = false}) async {
    Response res = await updateApp();
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String version = packageInfo.version; // 获取版本号
    if (version != res.data['version']) {
      loadingBot = BotToast.showCustomLoading(
          backgroundColor: Colors.black.withOpacity(0.35),
          toastBuilder: (cancel) {
            final theme = Theme.of(context);
            final primary = theme.colorScheme.primary;
            final isDark = theme.brightness == Brightness.dark;
            return Center(
              child: Material(
                color: Colors.transparent,
                child: Container(
                  width: 340,
                  padding:
                      const EdgeInsets.symmetric(horizontal: 24, vertical: 24),
                  decoration: BoxDecoration(
                    color: isDark ? theme.cardColor : Colors.white,
                    borderRadius: BorderRadius.circular(10),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.12),
                        blurRadius: 32,
                        offset: Offset(0, 8),
                      ),
                    ],
                  ),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Icon(Icons.system_update_alt_rounded,
                              color: primary, size: 28),
                          SizedBox(width: 10),
                          Text('发现新版本',
                              style: TextStyle(
                                  fontSize: 20,
                                  fontWeight: FontWeight.bold,
                                  color: primary)),
                          Spacer(),
                          Container(
                            decoration: BoxDecoration(
                              color: Colors.grey.withOpacity(0.12),
                              shape: BoxShape.circle,
                            ),
                            child: IconButton(
                                icon: Icon(Icons.close_rounded,
                                    color: Colors.grey[600]),
                                onPressed: () {
                                  loadingBot();
                                }),
                          ),
                        ],
                      ),
                      SizedBox(height: 8),
                      Divider(
                          height: 1,
                          thickness: 1,
                          color: theme.dividerColor.withOpacity(0.15)),
                      SizedBox(height: 12),
                      Row(
                        children: [
                          Text('版本号：',
                              style: TextStyle(
                                  fontSize: 15, color: theme.hintColor)),
                          Text('${res.data['version']}',
                              style: TextStyle(
                                  fontSize: 15,
                                  color: primary,
                                  fontWeight: FontWeight.w600)),
                        ],
                      ),
                      SizedBox(height: 10),
                      Text('更新内容',
                          style: TextStyle(
                              fontSize: 15,
                              fontWeight: FontWeight.w500,
                              color: theme.textTheme.bodyLarge?.color)),
                      SizedBox(height: 6),
                      Container(
                        constraints: BoxConstraints(maxHeight: 120),
                        child: ListView.separated(
                          shrinkWrap: true,
                          itemCount: res.data['update'].length,
                          separatorBuilder: (context, idx) =>
                              SizedBox(height: 6),
                          itemBuilder: (context, index) {
                            return Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Container(
                                  margin: EdgeInsets.only(top: 2),
                                  child: CircleAvatar(
                                    radius: 10,
                                    backgroundColor: primary.withOpacity(0.13),
                                    child: Icon(Icons.check_circle_rounded,
                                        color: primary, size: 16),
                                  ),
                                ),
                                SizedBox(width: 8),
                                Expanded(
                                  child: Text(
                                    '${index + 1}. ${res.data['update'][index]}',
                                    style: TextStyle(
                                        fontSize: 14,
                                        color:
                                            theme.textTheme.bodyMedium?.color),
                                  ),
                                ),
                              ],
                            );
                          },
                        ),
                      ),
                      SizedBox(height: 18),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Expanded(
                            child: ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                backgroundColor: primary,
                                foregroundColor: Colors.white,
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(18)),
                                padding: EdgeInsets.symmetric(
                                    horizontal: 22, vertical: 10),
                                elevation: 0,
                              ),
                              onPressed: () async {
                                if (await canLaunchUrl(Uri.parse(updateUrl))) {
                                  await launchUrl(Uri.parse(updateUrl));
                                } else {
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    SnackBar(
                                        content: Text('url error: $updateUrl')),
                                  );
                                }
                                loadingBot();
                              },
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Icon(
                                    Icons.download_rounded,
                                    size: 18,
                                    color: Colors.white,
                                  ),
                                  SizedBox(width: 6),
                                  Text('立即更新',
                                      style: TextStyle(
                                          fontWeight: FontWeight.bold)),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            );
          });
    }
    if (version == res.data['version'] && displayTips) {
      BotToast.showText(text: '当前已是最新版本');
    }
  }
}
